import { Dropdown, InputNumber, MenuProps, Table } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import '../../index.scss';
import { ContextType, TableData, tableProps } from '../../type';
export function TableComponent({ initialData, onDataChange }: tableProps) {
  const [dataSource, setDataSource] = useState<TableData[]>([
    { key: '1', x: null, y: null, z: null },
  ]);
  const [selectedKey, setSelectedKey] = useState<string>('');
  // 同步ref和state
  useEffect(() => {
    onDataChange?.(dataSource);
  }, [dataSource]);
  useEffect(() => {
    if (initialData && initialData.length === 0) {
      setDataSource([
        {
          key: '1',
          x: null,
          y: null,
          z: null,
        },
      ]);
    } else {
      setDataSource((prev) => {
        const lastRow = prev[prev.length - 1]; //获取最后一行
        // 如果最后一行是 null,就覆盖一下
        const isLastRowEmpty =
          lastRow &&
          lastRow.x === null &&
          lastRow.y === null &&
          lastRow.z === null;
        if (isLastRowEmpty) {
          // 如果最后一行全为 null，覆盖它（保留 key）
          const newData = [...prev];
          newData[newData.length - 1] = {
            ...lastRow, // 保留 key
            ...initialData[0], // 覆盖 x, y, z
          };
          if (initialData.length > 1) {
            return [...newData, ...initialData.slice(1)];
          }

          return newData;
        } else {
          return [...prev, ...initialData];
        }
      });
      // 说明导入了 csv 文件
    }
  }, [initialData]);

  const EditableCell = ({ value, onChange, recordKey, dataIndex }) => {
    return (
      <InputNumber
        key={`${recordKey}-${dataIndex}`}
        value={value}
        onChange={(val) => {
          onChange(val);
        }}
        size='small'
        className='w-full'
      />
    );
  };
  const contextMenu = [
    {
      key: ContextType.InsertRowAbove,
      label: '向上插入一行',
    },
    {
      key: ContextType.InsertRowBelow,
      label: '向下插入一行',
    },
    {
      key: ContextType.DeleteRow,
      label: '删除选中行',
    },
    {
      key: ContextType.DeleteAll,
      label: '删除所有行',
    },
  ];
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    const currentIndex = dataSource.findIndex(
      (item) => item.key === selectedKey,
    );
    if (currentIndex === -1) {
      return;
    }
    switch (key) {
      case ContextType.InsertRowAbove:
        setDataSource((prev) => {
          // 计算新key（不小于1）
          const newKey = Math.max(1, Number(selectedKey) - 1);
          const finalKey =
            newKey === Number(selectedKey)
              ? String(Math.max(...prev.map((item) => Number(item.key))) + 1)
              : String(newKey);
          const newList = [
            ...prev.slice(0, currentIndex),
            { key: finalKey, x: null, y: null, z: null },
            ...prev.slice(currentIndex),
          ];
          newList.forEach((item, index) => (item.key = String(index + 1)));
          return newList;
        });
        break;
      case ContextType.InsertRowBelow:
        setDataSource((prev) => {
          const newKey = Number(selectedKey) + 1;
          const finalKey =
            newKey === Number(selectedKey)
              ? String(Math.max(...prev.map((item) => Number(item.key))) + 1)
              : String(newKey);
          const newList = [
            ...prev.slice(0, currentIndex + 1),
            { key: finalKey, x: null, y: null, z: null },
            ...prev.slice(currentIndex + 1),
          ];
          newList.forEach((item, index) => (item.key = String(index + 1)));
          return newList;
        });
        break;
      case ContextType.DeleteRow:
        setDataSource((prev) => {
          const newList = prev.filter((item) => item.key !== selectedKey);
          newList.length === 0 &&
            newList.push({ key: '1', x: null, y: null, z: null });
          newList.forEach((item, index) => (item.key = String(index + 1)));
          return newList;
        });
        break;
      case ContextType.DeleteAll:
        setDataSource([{ key: '1', x: null, y: null, z: null }]);
        break;
    }
  };

  const rowNumberColumn = {
    title: '#',
    width: 60,
    align: 'center' as const,
    render: (_: any, __: TableData, index: number) => {
      return index + 1;
    },
  };
  const columns = useMemo(
    () => [
      rowNumberColumn,
      ...['X', 'Y', 'Z'].map((col) => {
        return {
          title: col,
          dataIndex: col.toLowerCase(),
          key: col.toLowerCase(),
          align: 'center' as const,
          render: (text, record) => {
            return (
              <EditableCell
                recordKey={record.key}
                dataIndex={col.toLowerCase()}
                value={text}
                onChange={(value) => {
                  setDataSource((prev) => {
                    const data = prev.map((item) =>
                      item.key === record.key
                        ? { ...item, [col.toLowerCase()]: value }
                        : item,
                    );
                    return data;
                  });
                }}
              />
            );
          },
        };
      }),
    ],
    [],
  );
  return (
    <>
      <Dropdown
        menu={{
          items: contextMenu,
          onClick: handleMenuClick,
        }}
        open={!!selectedKey}
        onOpenChange={(open) => {
          if (!open) {
            setSelectedKey('');
          }
        }}
        placement='bottom'
        trigger={['contextMenu']}>
        <div
          onContextMenu={(e) => {
            e.preventDefault();
          }}>
          <Table
            dataSource={dataSource}
            columns={columns}
            rowKey='key'
            onRow={(record) => ({
              onContextMenu: (e) => {
                e.preventDefault();
                setSelectedKey(record.key);
              },
            })}
            scroll={{ y: 'calc(80vh - 250px)' }}
            pagination={false}
            bordered
            size='small'
            className='custom-table-style'
          />
        </div>
      </Dropdown>
    </>
  );
}
